<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>debounce</title>
</head>

<body>
    <div class="main" style="height:2000px;width:100%"></div>
    <script>
        /**
         * @desc 函数防抖
         * @param func 函数
         * @param wait 延迟执行毫秒数
         * @param immediate true 表立即执行，false 表非立即执行
         */
        function debounce(func, wait, immediate) {
            var timeout;
            return function () {
                let context = this;
                let args = arguments;

                if (timeout) clearTimeout(timeout);
                if (immediate) {
                    var callNow = !timeout;
                    timeout = setTimeout(() => {
                        timeout = null; //取消上一个计时器
                    }, wait)
                    if (callNow) /* func.apply(context, args) //就是执行func的意思 */ func()
                } else {
                    timeout = setTimeout(function () {
                        /*  func.apply(context, args) */
                        func()
                    }, wait);
                }
            }
        }
        // 处理函数
        function handle() {
            console.log(Math.random());
        }
        // 滚动事件
        window.addEventListener('scroll', debounce(handle, 1000, true));
    </script>
</body>

</html>